package com.jwell.bigdata.utils

import android.content.Intent
import android.widget.Toast
import com.google.gson.JsonObject
import com.jwell.bigdata.R
import com.jwell.bigdata.base.IBaseView
import com.jwell.bigdata.comment.BigDataApp
import com.jwell.bigdata.ui.login.LoginActivity
import com.jwell.bigdata.utils.Utils
import org.json.JSONObject
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription

/**
 * Created by 76577 on 2018/3/12.
 */

/**
 * 观察者
 */
abstract class BaseSubscriber(private var baseView: IBaseView? = null) : Subscriber<JsonObject> {
    override fun onSubscribe(s: Subscription) {
        if (!Utils.isNetworkAvailable()) {
            //网络错误
            baseView?.hideProgress()
            onFailed(BigDataApp.instance.resources.getString(R.string.net_disable))
            s.cancel()
        }
        setSubscription(s)
        s.request(Long.MAX_VALUE)
    }

    //取消网络请求
    abstract fun setSubscription(s: Subscription)

    override fun onNext(t: JsonObject?) {
        var jsonObject = JSONObject(t.toString())
        if (BigDataApp.DEBUG) println(jsonObject)
        System.out.println(jsonObject.toString())
        if (jsonObject.getBoolean("success")) {
            try {
                succeed(jsonObject)
            } catch (e: Exception) {
                e.printStackTrace()
                onFailed(e.toString())
            }
        } else {
            onFailed(jsonObject.getString("message"))
        }
    }

    override fun onError(t: Throwable?) {
        baseView?.hideProgress()
        t?.printStackTrace()
        onFailed(t?.message.toString())
    }

    override fun onComplete() {
        baseView?.hideProgress()
    }

    abstract fun succeed(data: JSONObject)

    abstract fun onFailed(msg: String)

}